<template>
  <transition>
    <div class="take">
      <nav>
        <div class="left" v-show="show" @click="stopCamera">&lt;</div>
      </nav>

      <div class="demo">
        <div class="box">
          <video
            id="videoCamera"
            class="canvas"
            :width="videoWidth"
            :height="videoHeight"
            autoPlay
          ></video>
          <canvas
            id="canvasCamera"
            class="canvas"
            :width="videoWidth"
            :height="videoHeight"
          ></canvas>
        </div>
        <div class="btn">
          <button class="taking" v-show="show" @click="photographBtn"></button>
          <!-- <button v-if="os" @click="openCamera" v-show="false">
            打开摄像头
          </button>
          <button v-else @click="stopCamera" v-show="false">关闭摄像头</button> -->
        </div>
        <div class="back" @click="resetBtn" v-show="os">×</div>
        <button class="finish" @click="submitBtn" v-show="os">完成</button>
      </div>
    </div>
  </transition>
</template>
<script>
export default {
  data() {
    return {
      show: true,
      os: false,
      thisVideo: null,
      thisContext: null,
      thisCancas: null,
      imgSrc: "",
      videoWidth: 375,
      videoHeight: 667,
    };
  },
  created() {
    this.openCamera();
  },
  methods: {
    submitBtn() {
      console.log(this.imgSrc);
      this.$router.push('/chatdes')
    },
    // 调用摄像头权限
    openCamera() {
      //必须在model中render后才可获取到dom节点,直接获取无法获取到model中的dom节点
      this.$nextTick(() => {
        const _this = this;
        this.os = false; //切换成关闭摄像头
        this.thisCancas = document.getElementById("canvasCamera");
        this.thisContext = this.thisCancas.getContext("2d");
        this.thisVideo = document.getElementById("videoCamera");
        // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
        if (navigator.mediaDevices === undefined) {
          navigator.mediaDevices = {};
        }
        // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
        // 使用getUserMedia，因为它会覆盖现有的属性。
        // 这里，如果缺少getUserMedia属性，就添加它。
        if (navigator.mediaDevices.getUserMedia === undefined) {
          navigator.mediaDevices.getUserMedia = function (constraints) {
            // 首先获取现存的getUserMedia(如果存在)
            let getUserMedia =
              navigator.webkitGetUserMedia ||
              navigator.mozGetUserMedia ||
              navigator.getUserMedia;
            // 有些浏览器不支持，会返回错误信息
            // 保持接口一致
            if (!getUserMedia) {
              return Promise.reject(
                new Error("getUserMedia is not implemented in this browser")
              );
            }
            // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
            return new Promise(function (resolve, reject) {
              getUserMedia.call(navigator, constraints, resolve, reject);
            });
          };
        }
        const constraints = {
          audio: false,
          video: {
            width: _this.videoWidth,
            height: _this.videoHeight,
            transform: "scaleX(-1)",
          },
        };
        navigator.mediaDevices
          .getUserMedia(constraints)
          .then(function (stream) {
            // 旧的浏览器可能没有srcObject
            if ("srcObject" in _this.thisVideo) {
              _this.thisVideo.srcObject = stream;
            } else {
              // 避免在新的浏览器中使用它，因为它正在被弃用。
              _this.thisVideo.src = window.URL.createObjectURL(stream);
            }
            _this.thisVideo.onloadedmetadata = function (e) {
              console.log(e);
              _this.thisVideo.play();
            };
          })
          .catch((err) => {
            this.$message({
              message: "没有开启摄像头权限或浏览器版本不兼容",
              err,
              type: "warning",
            });
          });
      });
    },
    //拍照按钮
    photographBtn() {
      this.os = true;
      this.show = false;
      // 点击，canvas画图
      this.thisContext.drawImage(
        this.thisVideo,
        0,
        0,
        this.videoWidth,
        this.videoHeight
      );
      // 获取图片base64链接
      this.imgSrc = this.thisCancas.toDataURL("image/png");
    },
    //清空画布
    clearCanvas(id) {
      let c = document.getElementById(id);
      let cxt = c.getContext("2d");
      cxt.clearRect(0, 0, c.width, c.height);
    },
    //重置画布
    resetBtn() {
      this.os = false;
      this.show = true;
      this.imgSrc = "";
      this.clearCanvas("canvasCamera");
    },
    //关闭摄像头
    stopCamera() {
      this.$router.go(-1);
      if (this.thisVideo && this.thisVideo !== null) {
        this.thisVideo.srcObject.getTracks()[0].stop();
        // this.os = true; //切换成打开摄像头
      }
      console.log("!!!");
    },
  },
};
</script>
<style lang="scss" scoped>
.take {
  position: relative;
  width: 100vw;
  height: 100vh;
  background-color: black;

  nav {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
    width: 100%;
    // height: 45px;
    // background-color: black;
    color: white;
    text-align: center;
    line-height: 45px;

    .left {
      float: left;
      margin-left: 10px;
    }
  }

  .demo {
    width: 100%;

    .box {
      width: 100%;

      .videoCamera {
        position: absolute;
        width: 100%;
        height: 100%;
      }

      .canvas {
        position: absolute;
        width: 100%;
      }
    }

    .btn {
      position: absolute;
      bottom: 30px;
      width: 100%;
      display: flex;

      .taking {
        margin: auto;
        width: 70px;
        height: 70px;
        border-radius: 999px;
        border: none;
        box-shadow: 0 0 3px 6px rgba(128, 128, 128, 0.801);
      }
    }
    .back {
      position: absolute;
      top: 10px;
      left: 10px;
      font-size: 30px;
      color: #fff;
    }

    .finish {
      position: absolute;
      bottom: 30px;
      right: 20px;
      width: 60px;
      height: 30px;
      font-size: 14px;
      background-color: rgb(75, 174, 90);
      border-radius: 8px;
      color: #fff;
      border: none;
    }
  }

  .v-enter,
  .v-leave-to {
    transform: translateY(100%);
  }

  .v-enter-active,
  .v-leave-active {
    transition: all 3s linear;
  }

  .v-enter-to,
  .v-leave {
    transform: translateY(0);
  }
}
</style>